package pri.damai.xiaowu.common.log.trace;

import org.slf4j.MDC;
import pri.damai.xiaowu.common.core.util.SnowflakeId;

import java.util.Map;
import java.util.concurrent.Callable;

import static pri.damai.xiaowu.common.core.constant.TraceConstant.TRACE_ID;

/**
 *
 * @Desc
 * @Author DaMai
 * @Date 2021/5/26 9:16
 * 但行好事，莫问前程。
 */
public class ThreadMdcUtil {

    private static final SnowflakeId SNOWFLAKE_ID = new SnowflakeId(12L, 12L);

    public static String createTraceId() {
        return String.valueOf(SNOWFLAKE_ID.nextId());
    }

    public static void setTraceIdIfAbsent() {
        if (MDC.get(TRACE_ID) == null) {
            MDC.put(TRACE_ID, createTraceId());
        }
    }

    public static String getTraceId() {
        return MDC.get(TRACE_ID);
    }

    public static void setTraceId() {
        MDC.put(TRACE_ID, createTraceId());
    }

    public static void setTraceId(String traceId) {
        MDC.put(TRACE_ID, traceId);
    }

    public static void removeTrace() {
        MDC.remove(TRACE_ID);
    }

    public static <T> Callable<T> wrap(final Callable<T> callable, final Map<String, String> context) {
        return () -> {
            if (context == null) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
            }
            setTraceIdIfAbsent();
            try {
                return callable.call();
            } finally {
                MDC.clear();
            }
        };
    }

    public static Runnable wrap(final Runnable runnable, final Map<String, String> context) {
        return () -> {
            if (context == null) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
            }
            setTraceIdIfAbsent();
            try {
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }
}
